package btree;

import java.io.IOException;

import global.*;
import heap.InvalidSlotNumberException;
import diskmgr.*;

public class BTIndexPage extends BTSortedPage {
	public BTIndexPage(int keytype) throws ConstructPageException, IOException {
		super(keytype);
		setType(NodeType.INDEX);
	}

	public BTIndexPage(Page p, int keytype) {
		super(p, keytype);
		try {
			setType(NodeType.INDEX);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public BTIndexPage(PageId pageno, int keytype)
			throws ConstructPageException {
		super(pageno, keytype);
		try {
			setType(NodeType.INDEX);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public RID insertKey(KeyClass key, PageId pageNo) throws InsertRecException {
		KeyDataEntry entry = new KeyDataEntry(key, pageNo);
		return super.insertRecord(entry);
	}

	public KeyDataEntry getFirst(RID rid) throws IOException,
			InvalidSlotNumberException, KeyNotMatchException,
			NodeNotMatchException, ConvertException {
		rid = firstRecord();
		byte[] rec = getRecord(rid).getTupleByteArray();
		return BT
				.getEntryFromBytes(rec, 0, rec.length, keyType, NodeType.INDEX);

	}

	public KeyDataEntry getNext(RID rid) throws IOException,
			InvalidSlotNumberException, KeyNotMatchException,
			NodeNotMatchException, ConvertException {
		RID next = nextRecord(rid);
		rid = next;
		byte[] rec = getRecord(rid).getTupleByteArray();
		return BT
				.getEntryFromBytes(rec, 0, rec.length, keyType, NodeType.INDEX);

	}

	public PageId getPageNoByKey(KeyClass key)
			throws InvalidSlotNumberException, KeyNotMatchException,
			NodeNotMatchException, ConvertException, IOException {
		KeyDataEntry kde;
		RID rid = new RID();
		kde = getFirst(rid);
		KeyClass curkey = kde.key;
		boolean stop = false;
		while (BT.keyCompare(curkey, key) != 0 && !stop) {
			kde = getNext(rid);
			if (kde != null)
				curkey = kde.key;
			else
				stop = true;
		}
		if (stop != true)
			return ((IndexData) kde.data).getData();
		else
			return getPrevPage();

	}

	public PageId getLeftLink() throws IOException {
		return getPrevPage();
	}

	public void setLeftLink(PageId left) throws IOException {
		PageId pid = new PageId(left.pid);
		setPrevPage(pid);
	}
}
